package com.opendeepsearch.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opendeepsearch.state.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class JsonUtil {
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static List<SearchResult> parseTavilySearchResults(String jsonResponse) {
        List<SearchResult> results = new ArrayList<>();
        
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode resultsNode = rootNode.get("results");
            
            if (resultsNode != null && resultsNode.isArray()) {
                for (JsonNode resultNode : resultsNode) {
                    String title = getStringValue(resultNode, "title");
                    String url = getStringValue(resultNode, "url");
                    String content = getStringValue(resultNode, "content");
                    String snippet = getStringValue(resultNode, "snippet");
                    double relevanceScore = getDoubleValue(resultNode, "score");
                    
                    if (title != null && !title.trim().isEmpty()) {
                        results.add(new SearchResult(title, url, content, snippet, relevanceScore));
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Failed to parse Tavily search results", e);
        }
        
        return results;
    }

    private static String getStringValue(JsonNode node, String fieldName) {
        JsonNode fieldNode = node.get(fieldName);
        return fieldNode != null ? fieldNode.asText() : "";
    }

    private static double getDoubleValue(JsonNode node, String fieldName) {
        JsonNode fieldNode = node.get(fieldName);
        return fieldNode != null ? fieldNode.asDouble() : 0.0;
    }

    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            logger.error("Failed to serialize object to JSON", e);
            return "{}";
        }
    }
}